﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;
using Microsoft.JScript;
using System.Data.SqlClient;

namespace aliformerp
{
    public partial class Form1 : Form
    {
        public userinfo u1 = new userinfo();
        public static linqdbDataContext dt = new linqdbDataContext();
        public Form1()
        {
            InitializeComponent();
            textBox3.Text = ConfigurationManager.ConnectionStrings[1].Name.ToString();
            textBox4.Text = ConfigurationManager.ConnectionStrings[1].ConnectionString.ToString();
            textBox5.Text = ConfigurationManager.ConnectionStrings[1].ProviderName.ToString();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            //   ConfigurationManager.RefreshSection("ConnectionStrings");  
          //  int a = 1;
            if (textBox1.Text != string.Empty & textBox2.Text != string.Empty)
            {
                userinfo.account = textBox1.Text;
                userinfo.password = textBox2.Text;
            }
            else 
            {
                MessageBox.Show("用户名和密码不能为空");
            }
        string codeform1=    getcode();
        userinfo.acctk2 = getaccesstoken(codeform1);
        searchform srfm1 = new searchform();
        this.Hide();
        srfm1.Show();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private string getcode()
        {

            //richTextBox1.Text += "你的appkey是" + appKey;
            Dictionary<string, string> prm = new Dictionary<string, string>();

            prm.Add("client_id", userinfo.appKey);
            prm.Add("site", userinfo.site);
            prm.Add("redirect_uri", userinfo.redirect_uri);
            string aop_signature = userinfo.sign(prm, userinfo.secretkey);
            // richTextBox1.Text += "你的signature是" + aop_signature;

            string oauth = string.Format("http://gw.open.1688.com/auth/authorize.htm?client_id={0}&site=china&redirect_uri={1}&_aop_signature={2}", userinfo.appKey, userinfo.redirect_uri, aop_signature);
            //  System.Diagnostics.Process.Start(oauth);
            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest http = WebRequest.Create(oauth) as HttpWebRequest;
            http.Referer = oauth;
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            HttpWebResponse response = http.GetResponse() as HttpWebResponse;


            StreamReader reader = new StreamReader(response.GetResponseStream());

            string org = reader.ReadToEnd().ToString();
            //richTextBox1.Text += reader.ReadToEnd().ToString();
            string r = "<input type=\"hidden\" name=\"recordId\" value=\"(\\w+)(.\\w+)(.\\w+)(.\\w+)(.\\w+)";
            var match = Regex.Match(org, r);
            string rich = match.Groups[1].Value;
            rich += match.Groups[2].Value;
            rich += match.Groups[3].Value;
            rich += match.Groups[4].Value;
            rich += match.Groups[5].Value;
            //richTextBox1.Text += "你的recordId是" + rich;
            string r2 = "<input name='_csrf_token' type='hidden' value='(\\w+)";
            var match2 = Regex.Match(org, r2);
            string rich2 = match2.Groups[1].Value;
            //  richTextBox1.Text += "你的_csrf_token是" + rich2;

            HttpWebRequest http2 = WebRequest.Create(oauth) as HttpWebRequest;
            http2.Referer = oauth;
            http2.Method = "POST";
            http2.ContentType = "application/x-www-form-urlencoded";
            http2.AllowAutoRedirect = true;
            http2.KeepAlive = true;
            http2.CookieContainer = MyCookieContainer;
            string postBody = string.Format("action=AuthorizeAction&event_submit_do_accept_auth=submit&siteId=CN&authpage=client%2FchinaAuthrization&recordId={0}&_csrf_token={1}&account={2}&password={3}", rich, rich2, userinfo.account, userinfo.password);
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http2.ContentLength = postData.Length;

            using (Stream request2 = http2.GetRequestStream())
            {
                try
                {
                    request2.Write(postData, 0, postData.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    request2.Close();
                }
            }
            string code = string.Empty;

            HttpWebResponse response1 = http2.GetResponse() as HttpWebResponse;


            StreamReader reader1 = new StreamReader(response1.GetResponseStream());

            string codeuri = response1.ResponseUri.ToString();
            string codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
            //richTextBox1.Text += "你获取的code是:" + codeout;

            // return;


            // string lingpaigeturl = string.Format("https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/{0}?grant_type=authorization_code&need_refresh_token=true&client_id={1}&client_secret={2}&redirect_uri={3}&code={4}", appKey, appKey, secretkey, redirect_uri, codeout);
            // string lingpaigeturl2 = string.Format("http://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/{0}?", appKey);
            // getaccesstoken(codeout);
            //  wc.UploadDataAsync(new Uri(baseUrl), "POST", bytes);
            //   wc.UploadDataCompleted += wc_UploadDataCompleted;
            //  richTextBox1.Text += "你获取的令牌返回是:" + lingpaigeturl;       
            //  //  System.Diagnostics.Process.Start(lingpaigeturl);
            //NewMethod(MyCookieContainer);


            // webBrowser1.Url = new Uri(oauth);
            return codeout;
        }
        private acctk getaccesstoken(string codeout)
        {
            WebClient wc = new WebClient();
            string baseUrl = string.Format("https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/{0}", userinfo.appKey);
            string upstr1 = string.Format("client_id=1009066&redirect_uri=http%3A%2F%2Fgw.open.1688.com%2Fauth%2FauthCode.htm&code={0}&client_secret=aiN%2B~i~ab4_p&grant_type=authorization_code&need_refresh_token=true", codeout);
            string upstr = string.Format("client_id={0}&redirect_uri={1}&code={2}&client_secret={3}&grant_type=authorization_code&need_refresh_token=true", userinfo.appKey, Microsoft.JScript.GlobalObject.encodeURIComponent(userinfo.redirect_uri), codeout, Microsoft.JScript.GlobalObject.encodeURIComponent(userinfo.secretkey));
            string upout = Microsoft.JScript.GlobalObject.encodeURIComponent(upstr);
            byte[] bytes = Encoding.UTF8.GetBytes(upstr);
            // wc.BaseAddress = baseUrl;
            wc.Encoding = System.Text.Encoding.UTF8;
            wc.Headers.Add(HttpRequestHeader.Accept, "json");
            wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded; charset=UTF-8");
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
            //wc.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
            //wc.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            //wc.Headers.Add("Accept-Language", "zh-CN");
            //wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)");
            //wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            // wc.Headers.Add("ContentLength",bytes.Length.ToString()); 
            // wc.UploadStringCompleted += wc_UploadStringCompleted;
            //  wc.UploadStringAsync(new Uri(baseUrl), "POST",upstr1);
            string tkout = wc.UploadString(baseUrl, "POST", upstr);
            //richTextBox1.Text += "你获取的令牌返回是:" + tkout;
            string pattern1 = "{\"uid\":\"(?<uid>\\d+)\",\"aliId\":\"(?<aliId>\\d+)\",\"resource_owner\":\"(?<resource_owner>\\w+)\",\"memberId\":\"(?<memberId>\\S+)\",\"expires_in\":\"(?<expires_in>\\d+)\",\"refresh_token\":\"(\\w+)(.\\w+)(.\\w+)(.\\w+)(.\\w+)\",\"access_token\":\"(\\w+)(.\\w+)(.\\w+)(.\\w+)(.\\w+)\"}";
            Match match = Regex.Match(tkout, pattern1);
            //  richTextBox1.Text += match.Groups.Count;
            string refresh_token1 = string.Empty;
            for (int i = 1; i < 6; i++)
            {
                refresh_token1 += match.Groups[i].Value;
            }

            string access_token1 = string.Empty;
            for (int i = 6; i < 11; i++)
            {
                access_token1 += match.Groups[i].Value;
            }
            acctk acctk1 = new acctk()
            {
                access_token = access_token1,
                refresh_token = refresh_token1,
                uid = match.Groups["uid"].Value,
                aliId = match.Groups["aliId"].Value,
                resource_owner = match.Groups["resource_owner"].Value,
                memberId = match.Groups["memberId"].Value,
                expires_in = match.Groups["expires_in"].Value,
            };
            //   richTextBox1.Text += "是" +refresh_token + "是" + access_token + "是" + uid + "是" + aliId + "是" + resource_owner + "是" + memberId + "是" + expires_in;
            return acctk1;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != string.Empty | textBox2.Text != string.Empty)
            {
                MessageBox.Show("已有输入用户名密码，请核对后点登陆按钮");
            }
            else
            {
                string codeform1 = getcode();
                userinfo.acctk2 = getaccesstoken(codeform1);
                searchform srfm1 = new searchform();
                this.Hide();
                srfm1.Show();
            }
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string newName = textBox3.Text;
            string newConString = textBox4.Text;
            string newProviderName = textBox5.Text;
            bool isModified = false;    //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (ConfigurationManager.ConnectionStrings[newName] != null)
            {
                isModified = true;
            }
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings =
               new ConnectionStringSettings(newName, newConString, newProviderName);
            // 打开可执行的配置文件*.exe.config  
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // 如果连接串已存在，首先删除它  
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            // 将新的连接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("ConnectionStrings");
            this.Close();
            Application.Exit();
        }

        private void button4_Click(object sender, EventArgs e)
        {
           // this.DialogResult = DialogResult.OK;
            searchform srfm1 = new searchform();
            this.Hide();
            srfm1.Show();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string connStr =textBox4.Text;
            SqlConnection conn = new SqlConnection(connStr);
            try
            {
                conn.Open();
                MessageBox.Show("测试连接成功");

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("测试连接失败，原因" + ex.Data.ToString() + ex.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
